package com.persistent;

import cn.hutool.core.lang.Assert;
import com.industry.framework.common.redis.RedisUtils;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson;
import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 持久化存储多轮对话的历史上下文
 *
 * 多轮对话场景：
 * - 用户提问1 -> aiMessage回复 -> ChatMemoryStore存储 ChatMessage
 * - 用户提问2 -> 从Store中加载对话历史 -> LLM结合对话历史回复<用户提问2>内容
 */
@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {

    private final String MEMORY_ID_KEY = "CHAT_MEMORY_ID::";

    @Override
    public List<ChatMessage> getMessages(Object o) {
        Assert.notNull(o, "MemeryId must not be null");
        String cacheObject = RedisUtils.getCacheObject(MEMORY_ID_KEY + String.valueOf(o));
        if(StringUtils.isEmpty(cacheObject)){
            return new ArrayList<>();
        }
        return messagesFromJson(cacheObject);
    }

    @Override
    public void updateMessages(Object o, List<ChatMessage> list) {
        Assert.notNull(o, "MemeryId must not be null");
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        deleteMessages(o);
        RedisUtils.setCacheObject(MEMORY_ID_KEY + String.valueOf(o), messagesToJson(list) , Duration.ofDays(7L));
    }

    @Override
    public void deleteMessages(Object o) {
        RedisUtils.deleteObject(MEMORY_ID_KEY + String.valueOf(o));
    }
}
